package br.com.escolaespacocrianca.fineec.business;

import org.hibernate.Query;
import org.hibernate.Session;

import br.com.caelum.vraptor.ioc.Component;
import br.com.escolaespacocrianca.fineec.component.EncryptHandling;
import br.com.escolaespacocrianca.fineec.model.User;

@Component
public class UserBusiness extends EntityBusiness<User>  {

	public UserBusiness(Session session) {
		super(session, new User());
		this.session = session;
	}

	public User authenticate(String login,String password) {

		Query query = session.createQuery(
		"from User where login = :login and password = :password");
		
		query.setParameter("login", login);
		query.setParameter("password",EncryptHandling.encrypt( password ));
		
		return (User)query.uniqueResult();
	}

	@Override
	protected void updateEntityInformations(User user,User userToUpdate) {
		
		userToUpdate.setLogin(user.getLogin());
		if (!user.getPassword().isEmpty()){
			userToUpdate.setPassword( EncryptHandling.encrypt(user.getPassword()));
		}
		userToUpdate.setGroup( user.getGroup());
		userToUpdate.setName(user.getName());
		userToUpdate.setSuperUser(user.isSuperUser());
	}

	@Override
	protected void beforeDelete(User t) {
		// TODO Auto-generated method stub
		
	}


}
